package com.CMC.yhdeng;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.R.string;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.CMC.yhdeng.ExamUnitContent.ExamType;
import com.CMC.yhdeng.QuizContent.QCState;

public class Word2soundActivity extends QuizBaseActivity {
	 private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
	private Spinner spSpeechHint;
	private String answer;
	private int checkCount=0;
	private boolean bEndQuiz=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_word2sound);
		
		findViews();
		tunning();
		filterQuiz();
		
		findViewById(R.id.edtAnsInput).setVisibility(View.INVISIBLE);
		
		spSpeechHint=(Spinner)findViewById(R.id.speechHint);
		spSpeechHint.setVisibility(View.VISIBLE);
		checkVoiceRecognition();
	}
	
	protected void filterQuiz()
	{
		filterQuiz(ExamType.WORD2SOUND);
	}

	Boolean bPressed;
//	String sUploaStringdFilename;
	String sVoiceFilename;
	protected void findViews()
	{
		super.findViews();
		
		
		ivAnsMic.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ivAnsMic.setVisibility(View.INVISIBLE);
				
				speak(null);
				btnYes.setVisibility(View.VISIBLE);
				
			}
		});
		
	}
	
	protected void tunning()
	{
		View v=rlytInputArea.findViewById(R.id.btnCancel);
		v.setVisibility(View.INVISIBLE);
		
//		final View vYes=rlytInputArea.findViewById(R.id.btnYes);
		final View vYes=findViewById(R.id.btnYes);
		vYes.setVisibility(View.INVISIBLE);
		
		vYes.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//send voice file
				vYes.setVisibility(View.INVISIBLE);
				
				mr.stop();
				final String sFilename=curQuiz.id;
				new AsyncTask<String, integer, integer>(){

					@Override
					protected integer doInBackground(String... params) {
						try {
							postfile3(sFilename);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							Log.d("aaa",e.getMessage());
						}

						return null;
					}

					@Override
					protected void onPostExecute(integer result) {
						File f=new File(getMP4Filename(sFilename));
						
//						Log.d("aaa",String.format("delete %s is %s", f.getName(), Boolean.toString(f.delete())));
						super.onPostExecute(result);
					}
					
				}.execute("");
				Log.d("aaa","before answerChecked");
				answerChecked();
				Log.d("aaa","after answerChecked");
				clickYes();
				Log.d("aaa","after clickYes");
				if(curQuiz!=null && bEndQuiz==false)ivAnsMic.setVisibility(View.VISIBLE);	
				Log.d("aaa","bbbbbbbbbb");
			}
		});
		
		findViewById(R.id.imSpeaker).setVisibility(View.INVISIBLE);
		findViewById(R.id.edtAnsInput).setVisibility(View.INVISIBLE);
	}

	@Override
	protected void updateAnswerState() {
		
	}

	@Override
	protected void updateScenseAfterQuizInfoDownloaded() {
		super.updateScenseAfterQuizInfoDownloaded();
		setQuizContent(curQuiz);
		ivAnsMic.setVisibility(View.VISIBLE);
	}

	@Override
	protected void answerChecked() {
		super.answerChecked();
		if(curQuiz!=null)
		{
			setQuizContent(curQuiz);
		}else endQuiz();
	}

	protected String getAnswerString()
	{
		return curQuiz.title;
	}
	
//	@Override
//	protected void clickYes() {
//		// check answer
//		
////		etAnswer.setText(textMatchList.toString());
//		String answerStr=getAnswerString();
//			curQuiz.answerState=(answer!=null && answerStr.compareTo(answer)==0) ? QCState.CORRECT : QCState.WRONG;
//		
//		
//		popupAnswerResultView(curQuiz.answerState==QCState.CORRECT);
//		super.clickYes();
//	}
	
	 public void checkVoiceRecognition() {
		  // Check if voice recognition is present
		  PackageManager pm = getPackageManager();
		  List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
		    RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		  if (activities.size() == 0) {
//		   mbtSpeak.setEnabled(false);
//		   mbtSpeak.setText("Voice recognizer not present");
		   Toast.makeText(this, "Voice recognizer not present",
		     Toast.LENGTH_SHORT).show();
		  }
		 }
	 
	 MediaRecorder mr;
	 
	 @Override
	 protected void onStop() {
		 mr.release();
		 super.onStop();
	 }
	 @Override
	 protected void onStart() {
		 super.onStart();
		 mr=new MediaRecorder();
		 bPressed=false;
	 }
	 
//	 final String voiceFilename="testa.mp4"; 
	private String getMP4Filename(String sFilename) {
		
//		String s = String.format("%s/%s.mp4", this.getFilesDir().getPath(), curQuiz.id);

		 String s= String.format("/storage/sdcard1/%s.mp4",sFilename);
		return s;
	}
	 public void speak(View view) {
		 
		mr.reset();
		mr.setAudioSource(MediaRecorder.AudioSource.MIC);
		mr.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		String sFilename = getMP4Filename(curQuiz.id);
		mr.setOutputFile(sFilename);
		
		try {
			mr.prepare();
			mr.start();
			Toast.makeText(this, "開始錄音", 700).show();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.d("aaa",e.getMessage());
			Toast.makeText(this, e.getMessage(), 1000).show();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.d("aaa",e.getMessage());
			Toast.makeText(this, e.getMessage(), 1000).show();
		}
		 /////
//		 mr.setAudioSource(MediaRecorder.AudioSource.MIC);
//		 mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
//		 mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//		 sUploadFilename=String.format("%s.3gp", curQuiz.id);
//		 mr.setOutputFile(sUploadFilename);
//		 
//		 try {
//			mr.prepare();
//		} catch (IllegalStateException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		 mr.start();
		 
	 }
//	 public void speak(View view) {
//		  Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//		 
//		  // Specify the calling package to identify your application
////		  intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
////		    .getPackage().getName());
//		 
//		  intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
//				    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//		  // Display an hint to the user about what he should say.
//		  intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "hint here");
//		 
//		  
//		 
//		  // If number of Matches is not selected then return show toast message
////		  if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
////		   Toast.makeText(this, "Please select No. of Matches from spinner",
////		     Toast.LENGTH_SHORT).show();
////		   return;
////		  }
//		  intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
//		  //Start the Voice recognizer activity for the result.
//		  startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
//	 }

//	 ArrayList<String> textMatchList;
//	 @Override
//	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//	  if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//	 
//	   //If Voice recognition is successful then it returns RESULT_OK
//	   if(resultCode == RESULT_OK) {
//	 
//	    textMatchList = data
//	    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//	 
//	    if (!textMatchList.isEmpty()) {
//	     // If first Match contains the 'search' word
//	     // Then start web search.
//	     if (textMatchList.get(0).contains("search")) {
//	 
//	        String searchQuery = textMatchList.get(0);
//	                                           searchQuery = searchQuery.replace("search","");
//	        Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
//	        search.putExtra(SearchManager.QUERY, searchQuery);
//	        startActivity(search);
//	     } else {
//	         // populate the Matches
//	    	 textMatchList.add(0, "");
//	    	 final ArrayAdapter<String> ada=new ArrayAdapter<String>(this, 
//	 				R.layout.qts_spinner, textMatchList);
//	    	 
//	    	 spSpeechHint.setAdapter(ada);
//	    	 spSpeechHint.performClick();
//	    	 checkCount=0;
//	    	 
//	    	 spSpeechHint.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//				@Override
//				public void onItemSelected(AdapterView<?> arg0, View arg1,
//						int arg2, long arg3) {
//					
//					
//					
//					if(checkCount==0)
//					{
//						
//						checkCount++;
//						return;
//					}
//					TextView tv=(TextView)arg1;
//					answer=(String) tv.getText();
//					clickYes();
//					
//				}
//
//				@Override
//				public void onNothingSelected(AdapterView<?> arg0) {
//					// TODO Auto-generated method stub
//					
//				}
//	    		 
//			});
//	    	 
//	    	 
//	     }
//	 
//	    }
//	   //Result code for various error.
//	   }else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
//	    showToastMessage("Audio Error");
//	   }else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
//	    showToastMessage("Client Error");
//	   }else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
//	    showToastMessage("Network Error");
//	   }else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
//	    showToastMessage("No Match");
//	   }else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
//	    showToastMessage("Server Error");
//	   }
//	  super.onActivityResult(requestCode, resultCode, data);
//	 }

	public void postfile3(String sFilename) throws IOException {
		
		

		final String BOUNDARY = "==================================";
		final String HYPHENS = "--";
		final String CRLF = "\r\n";
		URL url = new URL(
				"http://www.urjotter.com/apis/index.php/exam/postFile");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST"); // method一定要是POST
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);

		// 把Content Type設為multipart/form-data
		// 以及設定Boundary，Boundary很重要!
		// 當你不只一個參數時，Boundary是用來區隔參數的
		conn.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + BOUNDARY);

		// 下面是開始寫參數
		String strContentDisposition = String
				.format("Content-Disposition: form-data; name=\"userfile\"; filename=\"%s\"",
						sFilename);
		String strContentType = "Content-Type: vedio";
		DataOutputStream dataOS;

		dataOS = new DataOutputStream(conn.getOutputStream());
		dataOS.writeBytes(HYPHENS + BOUNDARY + CRLF); // 寫--==================================
		dataOS.writeBytes(strContentDisposition + CRLF); // 寫(Disposition)
		dataOS.writeBytes(strContentType + CRLF); // 寫(Content Type)
		dataOS.writeBytes(CRLF);

		String sname=getMP4Filename(sFilename);
		FileInputStream fileInputStream = new FileInputStream(new File(sname));
		int iBytesAvailable = fileInputStream.available();
		byte[] byteData = new byte[iBytesAvailable];
		int iBytesRead = fileInputStream.read(byteData, 0, iBytesAvailable);
		while (iBytesRead > 0) {
			dataOS.write(byteData, 0, iBytesAvailable); // 開始寫內容
			iBytesAvailable = fileInputStream.available();
			iBytesRead = fileInputStream.read(byteData, 0, iBytesAvailable);
		}
		dataOS.writeBytes(CRLF);
		dataOS.writeBytes(HYPHENS + BOUNDARY + HYPHENS); // (結束)寫--==================================--
		fileInputStream.close();
		dataOS.flush();
		dataOS.close();

		Log.d("aaa", inputStream2String(conn.getInputStream()));
	}

	public String inputStream2String(InputStream is) throws IOException {

		Reader r = new InputStreamReader(is);
		StringBuilder sb = new StringBuilder();
		char[] cdata = new char[256];

		int n;
		n = r.read(cdata, 0, 256);

		String ss = String.valueOf(cdata);
		
		return ss;
	}


	@Override
	protected void endQuiz() {
		super.endQuiz();
		bEndQuiz=true;
		ivAnsMic.setVisibility(View.INVISIBLE);
		findViewById(R.id.btnYes).setVisibility(View.INVISIBLE);
		
	}


	@Override
	protected void showQuizResult() {
//		ivAnsMic.setVisibility(View.INVISIBLE);
		Toast.makeText(this, "測驗結束，請回上一頁", 800).show();
	}

	@Override
	protected void tick() {
		// TODO Auto-generated method stub
		
	}


	
	public void onbtn2(View v) {
		boolean b=findViewById(R.id.ivAnsMIc).performClick();
	}
	
	
	public void onbtn1(View v) {
	findViewById(R.id.btnYes).performClick();
	}
	
}
